package com.example.clear;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    TextView textTotal;
    TextView textLog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textTotal = findViewById(R.id.text_total);
        textLog = findViewById(R.id.text_log);
    }

    public void onMemoryClick(View view) {
        long availMemory = getAvailMemory(this) / (1024 * 1024);
        Log.d("ddd", "当前系统可用内存 : " + availMemory);
        Formatter.formatFileSize(this, availMemory);
        Log.d("ddd", "当前系统可用内存格式化 : " + availMemory);
        Long totalMemory = getTotalMemory(this) / (1024 * 1024);
        Log.d("ddd", "当前系统总内存 : " + totalMemory);
    }

    private long getAvailMemory(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(info);
        // info.availMem 当前系统可用内存
        return info.availMem;
    }

    // 从系统内存信息文件中读取总的内存：
    private Long getTotalMemory(Context context) {
        String str1 = "/proc/meminfo"; //系统内存信息文件
        String str2;
        String[] arrayOfString;
        long totalMemory = 0L;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader bufferedReader = new BufferedReader(localFileReader, 4096);
            str2 = bufferedReader.readLine(); // 读取memoryInfo的第一行，获取系统总内存大小
            if (!TextUtils.isEmpty(str2)) {
                arrayOfString = str2.split("\\s+");
                if (arrayOfString.length > 0) {
                    for (String num : arrayOfString) {
                        Log.d("ddd", "str2 : " + str2 + "--------- num : " + num);
                    }
                    // 获得系统总内存，单位KB KB或MB
                    totalMemory = Long.valueOf(arrayOfString[1]).intValue() * 1024;
                }
            }
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return totalMemory;
    }

    public ApplicationInfo getApplicationInfo(Context context, String processName) {
        if (processName == null) {
            return null;
        }
        List<ApplicationInfo> appList = context.getPackageManager().getInstalledApplications(PackageManager.MATCH_UNINSTALLED_PACKAGES);
        for (ApplicationInfo appInfo : appList) {
            if (processName.equals(appInfo.processName)) {
                return appInfo;
            }
        }
        return null;
    }

    public void onMemoryScanClick(View view) {
        AsyncTaskScan taskScan = new AsyncTaskScan(this, textTotal, textLog);
        taskScan.execute();


    }

    // 以下方法 为 跳转到手动打开权限的界面
    private void openSettingPackagePermActivity(Activity activity, String msg){
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        activity.startActivity(intent);
    }


    @TargetApi(Build.VERSION_CODES.M)
    public static boolean hasUsageStatsPermission(Context context) {
        //https://stackoverflow.com/a/42390614/878126
        AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        final int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), context.getPackageName());
        boolean granted = false;
        if (mode == AppOpsManager.MODE_DEFAULT)
            granted = (context.checkCallingOrSelfPermission(android.Manifest.permission.PACKAGE_USAGE_STATS) == PackageManager.PERMISSION_GRANTED);
        else
            granted = (mode == AppOpsManager.MODE_ALLOWED);
        return granted;
    }
}


